import React, { useState, useEffect } from 'react';
import {
    Text,
    Image,
    TouchableOpacity,
    View,
    Alert,
    Animated,
    Platform,
    TextInput,
    ScrollView,
    StyleSheet,
    RefreshControl,
    InteractionManager
} from 'react-native';
import {
    Tester,
    TestSuite,
    TestCase
} from '@rnoh/testerino';
import { useImageDimensions, useAppState, useLayout, useKeyboard, useDeviceOrientation, useBackHandler, useRefresh, useAccessibilityInfo, useInteractionManager } from '@react-native-community/hooks';
import Orientation from 'react-native-orientation-locker';

const HooksTest = () => {
    const {
        boldTextEnabled,
        screenReaderEnabled,
        reduceMotionEnabled,
        grayscaleEnabled,
        invertColorsEnabled,
        reduceTransparencyEnabled,
    } = useAccessibilityInfo()

    const [backText, setBackText] = useState('')
    const [refreshText, setRefreshText] = useState('下拉刷新')
    const [isLockedToPortrait, setIsLockedToPortrait] = useState(true);
    const { isRefreshing, onRefresh } = useRefresh(() => {
        return new Promise((resolve) => setTimeout(() => { resolve(setRefreshText('刷新成功')) }, 500))
    });
    const source = require('../../assets/react-native-community-hooks.jpg')
    const { dimensions, loading, error } = useImageDimensions(source)
    const { onLayout, ...layout } = useLayout()
    const [isBoldTextEnabled, setIsBoldTextEnabled] = useState(false)
    const [isscreenReaderEnabled, setIsscreenReaderEnabled] = useState(false)
    const [isReduceMotionEnabled, setIsReduceMotionEnabled] = useState(false)
    const [isGrayscaleEnabled, setIsGrayscaleEnabled] = useState(false)
    const [isInvertColorsEnabled, setIsInvertColorsEnabled] = useState(false)
    const [isReduceTransparencyEnabled, setIsReduceTransparencyEnabled] = useState(false)
    const [showBall, setShowBall] = useState(false)

    const useBackHandlerClick = (type: boolean) => {
        type ? setBackText('返回中断') : setBackText('')
    }

    useBackHandler(() => {
        if (backText) {
            return true
        }
        return false
    })

    const ballStart = () => {
        setShowBall(true)
    }

    useEffect(() => {
        let clearUseAccessibilityInfo = setTimeout(() => {
            setIsBoldTextEnabled(boldTextEnabled)
            setIsscreenReaderEnabled(screenReaderEnabled)
            setIsReduceMotionEnabled(reduceMotionEnabled)
            setIsGrayscaleEnabled(grayscaleEnabled)
            setIsInvertColorsEnabled(invertColorsEnabled)
            setIsReduceTransparencyEnabled(reduceTransparencyEnabled)
        }, 1000)
        return () => clearTimeout(clearUseAccessibilityInfo)
    }, [boldTextEnabled, screenReaderEnabled, reduceMotionEnabled, grayscaleEnabled, invertColorsEnabled, reduceTransparencyEnabled])

    const instructions = Platform.select({
        ios: "Press Cmd+R to reload,\n" + "Cmd+D or shake for dev menu",
        android:
            "Double tap R on your keyboard to reload,\n" +
            "Shake or press menu button for dev menu",
    });
    const useMount = (func: Function) => useEffect(() => func(), []);
    const Ball = ({ onShown }: any) => {
        const [opacity] = useState(new Animated.Value(0));
        const interactionReady = useInteractionManager();
        useEffect(() => {
            const handle = InteractionManager.createInteractionHandle();
            Animated.timing(opacity, {
                toValue: 1,
                duration: 3500,
                useNativeDriver: true,
            }).start(() => {
                InteractionManager.clearInteractionHandle(handle);
            });
        }, []);

        useEffect(() => {
            if (interactionReady) {
                onShown();
            }
        }, [interactionReady, onShown]);

        if (!showBall) return null;
        
        return <Animated.View style={[styles.ball, { opacity }]} />;
    };

    const toggleOrientation = () => {
        if (isLockedToPortrait) {
            Orientation.lockToLandscape();
        } else {
            Orientation.lockToPortrait();
        }
        setIsLockedToPortrait(!isLockedToPortrait);
    };

    return (
        <Tester style={{ flex: 1 }}>
            <ScrollView refreshControl={
                <RefreshControl
                    refreshing={isRefreshing}
                    onRefresh={onRefresh}
                />
            }>
                <TestSuite name="useAccessibilityInfo">
                    <TestCase itShould="some-hooks" tags={['useAccessibilityInfo']}>
                        <Text> boldTextEnabled: {`${isBoldTextEnabled}`} </Text>
                        <Text> screenReaderEnabled: {`${isscreenReaderEnabled}`}</Text>
                        <Text> reduceMotionEnabled: {`${isReduceMotionEnabled}`}</Text>
                        <Text> grayscaleEnabled: {`${isGrayscaleEnabled}`}</Text>
                        <Text> invertColorsEnabled: {`${isInvertColorsEnabled}`}</Text>
                        <Text> reduceTransparencyEnabled: {`${isReduceTransparencyEnabled}`}</Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useRefresh">
                    <TestCase itShould="some-hooks" tags={['useRefresh']}>
                        <Text> {refreshText} </Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useBackHandler">
                    <TestCase itShould="some-hooks" tags={['useBackHandler']}>
                        <Text> {backText} </Text>
                        <TouchableOpacity
                            onPress={() => useBackHandlerClick(false)}
                            style={styles.useBackHandlerBtn}>
                            <Text style={styles.btnText}>useBackHandler (false)</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => useBackHandlerClick(true)}
                            style={styles.useBackHandlerBtn}>
                            <Text style={styles.btnText}>useBackHandler (true)</Text>
                        </TouchableOpacity>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useDeviceOrientation">
                    <TestCase itShould="some-hooks" tags={['useDeviceOrientation']}>
                        <Text>判断是横屏(landscape)还是纵屏(portrait)：{useDeviceOrientation()} </Text>
                        <TouchableOpacity
                            onPress={toggleOrientation}
                            style={styles.useBackHandlerBtn}>
                            <Text style={styles.btnText}>
                                {isLockedToPortrait ? '切换到横屏' : '切换到竖屏'}
                            </Text>
                        </TouchableOpacity>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useImageDimensions">
                    <TestCase itShould="some-hooks" tags={['useImageDimensions']}>
                        {
                            (loading || error || !dimensions) ? <Text>失败</Text> : <View>
                                <Image
                                    style={{ width: 100, height: 100, margin: 4, borderRadius: 8 }}
                                    source={source}
                                />
                            </View>
                        }
                        <Text>返回图片宽高的比列,高,宽：{JSON.stringify(dimensions)} </Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useAppState">
                    <TestCase itShould="some-hooks" tags={['useAppState']}>
                        <Text>返回应用程序状态：{useAppState()} </Text>
                        <Text>状态有： "active" | "background" | "inactive" | "unknown" | "extension"</Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useLayout">
                    <TestCase itShould="some-hooks" tags={['useLayout']}>
                        <Text onLayout={onLayout}>返回元素的坐标和宽高 : {JSON.stringify(layout)}</Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="useKeyboard">
                    <TestCase itShould="some-hooks" tags={['useKeyboard']}>
                        <TextInput />
                        <Text>返回键盘收起状态，和键盘相关信息{JSON.stringify(useKeyboard())}</Text>
                    </TestCase>
                </TestSuite>

                <TestSuite name="InteractionManager">
                    <TestCase itShould="some-hooks" tags={['useKeyboard']}>
                        <Text>{instructions}</Text>
                        {showBall && <Ball onShown={() => Alert.alert("Animation is done")} />}
                        <TouchableOpacity
                            onPress={() => ballStart()}
                            style={styles.useBackHandlerBtn}>
                            <Text style={styles.btnText}>InteractionManager</Text>
                        </TouchableOpacity>
                    </TestCase>
                </TestSuite>
                <View style={{ height: 200 }}></View>
            </ScrollView>
        </Tester>
    );
}

const styles = StyleSheet.create({
    useBackHandlerBtn: {
        borderRadius: 6,
        height: 36,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        margin: 10,
        backgroundColor: 'rgb(61, 176, 236)',
    },
    TextInput: {
        height: 40,
        borderColor: '#fff',
        borderWidth: 1,
        borderRadius: 4,
        width: '90%',
        backgroundColor: '#fff'
    },
    btnText: { fontWeight: 'bold', color: '#fff', fontSize: 20 },
    container: { flex: 1 },
    ball: {
        width: 100,
        height: 100,
        backgroundColor: "salmon",
        borderRadius: 100,
    },
});

export const displayName = 'react-native-community/hooks';
export const framework = 'React';
export const category = 'UI';
export const title = 'react-native-community/hooks';
export const documentationURL = "https://github.com/react-native-community/hooks";
export const description = 'React Native Community Hooks';

export const examples = [
    {
        title: 'React Native Community Hooks',
        render: function () {
            return <HooksTest />;
        },
    },
];
